package com.itheima.aspect;


import com.itheima.anno.EmpLoginLogOperation;
import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.ObjectError;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Slf4j
@Aspect
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;


    @Around("execution(* com.itheima.controller.LoginController.login(com.itheima.pojo.Emp))")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("===== 开始记录登录日志 =====");

        try {
            // 1. 获取参数
            Emp empParam = (Emp) joinPoint.getArgs()[0];
            log.info("登录用户: {}", empParam.getUsername());

            // 2. 执行方法并计时
            long start = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();
            long time = System.currentTimeMillis() - start;

            // 3. 处理结果
            if (proceed instanceof Result) {
                Result result = (Result) proceed;
                EmpLoginLog login = new EmpLoginLog();
                login.setUsername(empParam.getUsername());
                login.setPassword(empParam.getPassword());
                login.setLoginTime(LocalDateTime.now());
                login.setCostTime(time);

                int code = result.getCode();
                login.setIsSuccess((short)code);

                LoginInfo info = (LoginInfo) result.getData();
                if (info != null) {
                    login.setJwt(info.getToken());
                }

/*
                if (result.getCode() == 200 && result.getData() instanceof LoginInfo) {
                    login.setJwt(((LoginInfo) result.getData()).getToken());
                }
*/

                // 4. 记录日志
                log.info("准备插入日志: {}", log);
                try {
                    empLoginLogMapper.insertLog(login);
                    log.info("日志插入成功");
                } catch (Exception e) {
                    log.error("插入日志失败", e);
                    throw e;
                }
            }

            return proceed;
        } finally {
            log.info("===== 结束日志记录 =====");
        }
    }
}
